//
//  CycCarModel.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/10.
//

#import "CycCarModel.h"
#import "BaseRequest.h"
#import "DeviceRequest.h"
#import "CycBLEManager.h"
#import "CycBLEMessageCenter.h"

@implementation CycCarModel
- (instancetype)initWithPeripheral:(CBPeripheral *)peripheral {
    if (self = [super init]) {
        self.peripheral = peripheral;
        self.bleName = peripheral.name;
        self.carName = peripheral.name;
        self.mac = [peripheral.name substringFromIndex:5];
        [CycBLEManager sharedManager].receiveDataoutBlock = ^(NSData *data) {
            [self paresData:data];
        };
    }
    return self;
}

// 解析数据
- (void)paresData:(NSData *)data {
    uint8_t cmd;
    [data getBytes:&cmd range:NSMakeRange(2, 1)];
    int8_t length;
    [data getBytes:&length range:NSMakeRange(3, 1)];
    NSData *value = [data subdataWithRange:NSMakeRange(4, length)];
    if(0xa0 == cmd){ // 车辆型号
        self.model = [self convertDataToHexStr:value];
    }
    if(0xa1 == cmd){ // 总里程0x0700-7000700  0x64 6464000
        NSString *hexStr = [self hexStringFromData:value];
        self.totalmileage = [hexStr floatValue];
    }
    if(0xa2 == cmd){ // 单次里程0.3
        NSString *hexStr = [self hexStringFromData:value];
        self.danci = [hexStr floatValue];
        NSLog(@"A2******************: %lu",(unsigned long)self.danci);
    }
    if(0xa3 == cmd){ // 当前可骑行距离
        NSString *hexStr = [self hexStringFromData:value];
        self.canmileage = [hexStr floatValue];
        NSLog(@"A3******************: %lu",(unsigned long)self.canmileage);
    }
    if(0xa5 == cmd){ // 当前档位
        NSString *hexStr = [self hexStringFromData:value];
        self.curr_dangwei = [hexStr integerValue];
        NSLog(@"A5******************: %lu",(unsigned long)self.curr_dangwei);
    }
    if(0xa6 == cmd){ // 当前速度
        NSString *hexStr = [self hexStringFromData:value];
        self.curr_sudu = [hexStr floatValue];
        NSLog(@"A6******************: %lu",(unsigned long)self.curr_sudu);
    }
    if(0xa7 == cmd){// 平均速度
        NSString *hexStr = [self hexStringFromData:value];
        self.avg_sudu = [hexStr floatValue];
        NSLog(@"A7******************: %lu",(unsigned long)self.avg_sudu);
    }
    if(0xa8 == cmd){ // 最大速速
        NSString *hexStr = [self hexStringFromData:value];
        self.zuida_sudu = [hexStr floatValue];
        NSLog(@"A8******************: %lu",(unsigned long)self.zuida_sudu);
    }
    if(0xd2 == cmd){ // 仪表型号
        NSString *str = [self convertDataToHexStr:value];
        NSLog(@"D2******************: %@",str);
    }
    if(0xd3 == cmd){ // 仪表sn
        self.sn = [self convertDataToHexStr:value];
        NSLog(@"D3******************: %@",self.sn);
        
    }
    if(0xd5 == cmd){ // 蓝牙名称
        self.bleName = [self convertDataToHexStr:value];
        NSLog(@"D5******************: %@",self.bleName);
    }
    if(0xb3 == cmd){ // 电量
        NSString *hexStr = [self hexStringFromData:value];
        self.electricity = [hexStr integerValue];
        NSLog(@"B3******************: %lu",(unsigned long)self.electricity);
        NSMutableDictionary *dataParam = [NSMutableDictionary dictionary];
        [dataParam setValue:@(self.electricity) forKey:@"electricity"];
        [dataParam setValue:@(self.zuida_sudu) forKey:@"zuida_sudu"];
        [dataParam setValue:@(self.avg_sudu) forKey:@"avg_sudu"];
        [dataParam setValue:@(self.curr_sudu) forKey:@"curr_sudu"];
        [dataParam setValue:@(self.curr_dangwei) forKey:@"curr_dangwei"];
        [dataParam setValue:@(self.danci) forKey:@"danci"];
        [dataParam setValue:@(self.canmileage) forKey:@"canmileage"];
        [dataParam setValue:@(self.totalmileage) forKey:@"totalmileage"];
        NSDictionary *parm1 = @{
                               @"flag":@"蓝牙数据*",
                               @"content":[NSString stringWithFormat:@"*参数*：%f",self.danci]
                               };
        NSString *url1 = [NSString stringWithFormat:@"%@%@",BaseUrl,Cyc_API_Test];
        [BaseRequest baseGET_New:url1 cache:NO autoHideLoading:NO parms:parm1 request:^(id  _Nullable resultObject, NSError * _Nullable error) {
        }];

        [DeviceRequest updateDeviceDataWithSn:self.mac name:self.bleName model:self.model data:[dataParam copy] result:^(BOOL ret) {
            NSDictionary *parm = @{
                                   @"flag":@"更新蓝牙数据",
                                   @"content":[NSString stringWithFormat:@"更新蓝牙数据：%d",ret]
                                   };
            NSString *url = [NSString stringWithFormat:@"%@%@",BaseUrl,Cyc_API_Test];
            [BaseRequest baseGET_New:url cache:NO autoHideLoading:NO parms:parm request:^(id  _Nullable resultObject, NSError * _Nullable error) {
                
            }];
        }];
        
    }
}

- (NSString *)convertDataToHexStr:(NSData *)data {
    NSLog(@"要转化的ascll码 =============== %@",data);
    NSString *str = @"";
    Byte *bytes = (Byte *) malloc(data.length);
    [data getBytes:bytes length:data.length];
    
    for (int i = 0; i < data.length; i ++) {
        char temp = bytes[i];
        str = [str stringByAppendingString:[NSString stringWithFormat:@"%c",temp]];
    }
    NSLog(@"ascll码转化的结果 ===============%@",str);
    
    return str;
    
}

//data转换为十六进制的string
-(NSString *)hexStringFromData:(NSData *)myD{
    
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    NSLog(@"hex = %@",hexStr);
    return [self hexToStr:[self covertToStr:hexStr]];
}
//十六进制转十进制
- (NSString *)hexToStr:(NSString *)hexStr{
    NSString *str = [NSString stringWithFormat:@"%lu",strtoul([hexStr UTF8String], 0, 16)];
    return str;
}
#pragma mark - 高低位转换
- (NSString *)covertToStr:(NSString *)str{
    NSString *tmpStr = str;
    NSMutableArray *tmpArra = [NSMutableArray array];
    for (int i = 0 ;i<str.length/2 ;i+=2)
    {
        NSString *str = [tmpStr substringWithRange:NSMakeRange(i, 2)];
        [tmpArra addObject:str];
    }
    NSArray *lastArray = [[tmpArra reverseObjectEnumerator] allObjects];
    NSMutableString *lastStr = [NSMutableString string];
    for (NSString *str in lastArray)
    {
        [lastStr appendString:str];
    }
    return lastStr;
}

//十六进制的string为转换data
- (NSData *) stringToHexData:(NSString *)hexStr
{
    int len = [hexStr length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    for (i=0; i < [hexStr length] / 2; i++) {
        byte_chars[0] = [hexStr characterAtIndex:i*2];
        byte_chars[1] = [hexStr characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}

- (void)getCarMessageWithCmd:(uint8_t)cmd retBlock:(void(^)(NSData *, NSError *))retBlock {
    CycBleMessage *message = [[CycBleMessage alloc] initWithTarget:0x0d cmd:cmd data:nil];
    [[CycBLEMessageCenter sharedInstance] sendMessage:message withTimeOut:6 completion:^(NSError * _Nullable error, CycBleMessage * _Nullable responseData) {
        NSLog(@"responseData:%@",[self hexStringFromData:responseData.body.data]);
        retBlock(responseData.body.data,error);
    }];
}

@end
